package com.itheima.reggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author ljj
 * @create 2022-11-16-11:45
 */
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
    log.info("来了insert");

        hasAndSet(metaObject,"createTime",LocalDateTime.now());
        hasAndSet(metaObject,"updateTime", LocalDateTime.now());
        Long currentId = BaseContext.getCurrentId();
        hasAndSet(metaObject,"createUser", currentId);
        hasAndSet(metaObject,"updateUser", currentId);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("来了update");
        long id = Thread.currentThread().getId();
        log.info("updateFill id:{}",id);
        hasAndSet(metaObject,"updateTime", LocalDateTime.now());
        Long currentId = BaseContext.getCurrentId();
        hasAndSet(metaObject,"updateUser", currentId);
    }
    public void hasAndSet(MetaObject metaObject,String key,Object value) {
        if (metaObject.hasSetter(key)){
            metaObject.setValue(key, value);
        }
    }
}
